<template>
  <el-dialog :title="ruleId ? '编辑报警规则' : '新增报警规则'" v-model="visible" width="800px" @close="handleClose">
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="报警数据类型：" prop="alertDataType">
            <el-radio-group v-model="formData.alertDataType">
              <el-radio v-for="(item, index) in dataType" :key="index" :label="item.id">{{ item.value }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="报警规则名称：" prop="alertRuleName">
            <el-input v-model="formData.alertRuleName" placeholder="请输入" maxlength="20" show-word-limit />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="持续周期：" prop="duration">
            <el-select v-model="formData.duration" clearable filterable placeholder="请选择">
              <el-option v-for="(item, index) in continuePeriodData" :key="index" :value="item.value" :label="item.label" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="运算符：" prop="operator">
            <el-select v-model="formData.operator" clearable filterable placeholder="请选择">
              <el-option v-for="(item, index) in operatorData" :key="index" :value="item.value" :label="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="阈值：" prop="value">
            <el-input-number v-model="formData.value" :step="1" :max="99999999" placeholder="0.0" :precision="1" style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="报警生效时段：" prop="alertEffectivePeriod">
            <el-time-picker v-model="formData.alertEffectivePeriod" is-range range-separator="-" value-format="HH:mm:ss" style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="报警沉默周期：" prop="alertSilentPeriod">
            <el-select v-model="formData.alertSilentPeriod" clearable filterable placeholder="请选择">
              <el-option v-for="(item, index) in silenceCycleData" :key="index" :value="item.value" :label="item.id > 4 ? item.value + '小时' : item.value + '分钟'" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleSub">提交</el-button>
        <el-button @click="handleCancel">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup name="AlertRuleDetails">
import { ref, onMounted, watch, defineProps, defineEmits, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { getNum } from '@/utils/validate';
import dayjs from 'dayjs';
const props = defineProps({ id: { type: [String, Number], default: null }, visible: { type: Boolean, default: false } });
const emit = defineEmits(['close', 'update:visible']);
const visible = computed({
  get: () => props.visible,
  set: v => emit('update:visible', v)
});
// 接口
import {
  getAlertRule,
  addAlertRule,
  updateAlertRule,
} from '@/api/nursing/alertRule';
// 基础数据
import {
  operatorData,
  continuePeriodData,
  dataType,
  silenceCycleData,
} from '@/utils/commonData';
// ------定义变量------
const ruleId = ref(props.id);
const formData = ref({
  alertDataType: '',
  alertRuleName: '',
  duration: '',
  operator: '',
  value: '',
  alertEffectivePeriod: ['00:00:00', '23:59:59'],
  alertSilentPeriod: '',
  status: 1,
});
const publishedData = ref([]); // 功能
const itemData = ref([]); // 模块
const listData = ref(); // 关联设备
const published = ref({});
const formRef = ref(null);
// 表单校验
const rules = {
  alertRuleName: [
    {
      required: true,
      message: '报警规则名称为空，请输入报警规则名称',
      trigger: 'blur',
    },
  ],
  operator: [
    {
      required: true,
      message: '运算符为空，请选择运算符',
      trigger: 'change',
    },
  ],
  value: [
    {
      required: true,
      message: '阈值为空，请输入阈值',
      trigger: 'change',
    },
  ],
  duration: [
    {
      required: true,
      message: '持续周期为空，请选择持续周期',
      trigger: 'change',
    },
  ],
  alertDataType: [
    {
      required: true,
      message: '报警数据类型为空，请选择报警数据类型',
      trigger: 'change',
    },
  ],
  alertEffectivePeriod: [
    {
      required: true,
      message: '报警生效时段为空，请选择报警生效时段',
      trigger: 'change',
    },
  ],
  alertSilentPeriod: [
    {
      required: true,
      message: '报警沉默周期为空，请选择报警沉默周期',
      trigger: 'change',
    },
  ],
};
// 生命周期
onMounted(() => {
  if (ruleId.value) {
    getFromData();
  }
});
// 监听路由变化，刷新页面内容
watch(() => props.id, (val) => {
  ruleId.value = val;
  if (val) getFromData();
  else resetForm();
});
function handleClose() {
  emit('update:visible', false);
  emit('close', false);
}
// ------定义方法------
// 获取详情
const getFromData = async () => {
  const res = await getAlertRule(ruleId.value);
  if (res.code === 200) {
    formData.value = res.data;
    formData.value.duration = String(formData.value.duration ?? '');
    formData.value.value = String(res.data.value ?? '');
    // 处理报警生效时段
    if (typeof res.data.alertEffectivePeriod === 'string' && res.data.alertEffectivePeriod.includes('~')) {
      formData.value.alertEffectivePeriod = res.data.alertEffectivePeriod.split('~').map(s => s.trim());
    } else if (Array.isArray(res.data.alertEffectivePeriod)) {
      formData.value.alertEffectivePeriod = res.data.alertEffectivePeriod;
    } else {
      formData.value.alertEffectivePeriod = ['00:00:00', '23:59:59'];
    }
    // 处理报警沉默周期
    formData.value.alertSilentPeriod = String(res.data.alertSilentPeriod ?? '');
  }
};
// 提交表单
const handleSub = () => {
  formRef.value.validate(async (valid) => {
    if (valid === true) {
      const form = formData.value;
      const num = form.alertSilentPeriod;
      if (typeof num === 'number') {
        form.alertSilentPeriod = num;
      } else {
        form.alertSilentPeriod = Number(getNum(num));
      }
      const obj = {
        ...form,
        alertSilentPeriod: form.alertSilentPeriod,
        alertDataType: Number(form.alertDataType),
        alertEffectivePeriod: form.alertEffectivePeriod.join('~'),
        duration:
          typeof num === 'number' ? form.duration : Number(form.duration),
        value: Number(form.value),
      };
      let res;
      if (ruleId.value) {
        res = await updateAlertRule(obj);
      } else {
        res = await addAlertRule(obj);
      }
      if (res && res.code === 200) {
        ElMessage.success(ruleId.value ? '编辑成功' : '添加成功');
        emit('update:visible', false);
        emit('close', true);
      }
    }
  });
};
// 触发沉默周期
const handlePeriod = (val) => {
  // 保证 alertSilentPeriod 始终为字符串
  formData.value.alertSilentPeriod = String(val.value);
  if (val.id > 4) {
    formData.value.remark = val.value * 60;
  } else {
    formData.value.remark = val.value;
  }
};
// 时间段选择
const handleRangePick = (v) => {
  // 保证 alertEffectivePeriod 始终为长度为2的字符串数组
  if (Array.isArray(v) && v.length === 2) {
    formData.value.alertEffectivePeriod = v.map(s => (typeof s === 'string' ? s : '00:00:00'));
  } else {
    formData.value.alertEffectivePeriod = ['00:00:00', '23:59:59'];
  }
};
// 阈值
const textBlur = () => {
  const data = Number(formData.value.value);
  // 最大值设置
  if (data > 99999999) {
    formData.value.value = '99999999';
  }
};
// 返回
const handleReturn = () => {
  emit('update:visible', false);
  emit('close', false);
};
function handleCancel() {
  emit('update:visible', false);
  emit('close', false);
}
function resetForm() {
  formData.value = {
    alertDataType: '',
    alertRuleName: '',
    duration: '',
    operator: '',
    value: '',
    alertEffectivePeriod: ['00:00:00', '23:59:59'],
    alertSilentPeriod: '',
    status: 1,
  };
  ruleId.value = null;
}

</script>
